package com.ashley.phonemsn

import android.annotation.SuppressLint
import android.app.Notification
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.Service
import android.content.Context
import android.content.Intent
import android.os.Build
import android.os.IBinder
import android.telecom.Call
import android.telecom.CallScreeningService
import android.telecom.TelecomManager
import android.util.Log
import androidx.core.app.NotificationCompat

/**
 * 电话接听服务
 * 用于拦截和接听来电
 */
class CallAnswerService : Service() {
    private val TAG = "CallAnswerService"
    private val CHANNEL_ID = "call_answer_channel"
    private val NOTIFICATION_ID = 1001

    private var telecomManager: TelecomManager? = null
    private var currentCall: Call? = null

    @SuppressLint("ForegroundServiceType")
    override fun onCreate() {
        super.onCreate()
        Log.d(TAG, "电话接听服务已创建")
        
        // 初始化TelecomManager
        telecomManager = getSystemService(Context.TELECOM_SERVICE) as? TelecomManager
        
        // 创建前台服务通知
        createNotificationChannel()
        startForeground(NOTIFICATION_ID, createNotification())
    }

    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        Log.d(TAG, "电话接听服务已启动")
        
        // 处理来电拦截和接听
        intent?.let {
            when (it.action) {
                ACTION_ANSWER_CALL -> {
                    val phoneNumber = it.getStringExtra(EXTRA_PHONE_NUMBER)
                    answerIncomingCall(phoneNumber)
                }
                ACTION_REJECT_CALL -> {
                    val phoneNumber = it.getStringExtra(EXTRA_PHONE_NUMBER)
                    rejectIncomingCall(phoneNumber)
                }
            }
        }
        
        return START_STICKY
    }

    override fun onBind(intent: Intent?): IBinder? = null

    /**
     * 接听来电
     */
    private fun answerIncomingCall(phoneNumber: String?) {
        try {
            Log.d(TAG, "尝试接听来电: $phoneNumber")
            
            // 使用TelecomManager接听电话
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                telecomManager?.let { telecom ->
                    // 检查是否有来电
                    if (telecom.isInCall) {
                        // 对于Android O及以上版本，使用反射或其他方式获取当前通话
                        // 这里简化处理，直接使用Intent方式接听
                        answerCallUsingIntent(phoneNumber)
                        Log.d(TAG, "成功接听来电: $phoneNumber")
                    } else {
                        Log.w(TAG, "当前没有来电需要接听")
                    }
                }
            } else {
                // Android O以下版本的处理
                answerCallUsingIntent(phoneNumber)
            }
        } catch (e: SecurityException) {
            Log.e(TAG, "接听电话权限不足", e)
        } catch (e: Exception) {
            Log.e(TAG, "接听电话失败", e)
        }
    }
    
    /**
     * 使用Intent方式接听电话
     */
    private fun answerCallUsingIntent(phoneNumber: String?) {
        try {
            // 创建接听电话的Intent - 使用有效的系统动作
            val answerIntent = Intent("android.intent.action.ANSWER")
            answerIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
            
            // 发送广播接听电话
            sendBroadcast(answerIntent)
            
            Log.d(TAG, "使用Intent方式接听来电: $phoneNumber")
        } catch (e: Exception) {
            Log.e(TAG, "使用Intent接听电话失败", e)
            // 备选方案：使用反射或其他方式
            answerCallFallback(phoneNumber)
        }
    }
    
    /**
     * 接听电话的备选方案
     */
    private fun answerCallFallback(phoneNumber: String?) {
        try {
            // 使用反射调用TelecomManager的接听方法
            try {
                val telecomManagerClass = Class.forName("android.telecom.TelecomManager")
                val method = telecomManagerClass.getMethod("acceptRingingCall")
                method.invoke(telecomManager)
                Log.d(TAG, "使用反射接听来电: $phoneNumber")
                return
            } catch (e: Exception) {
                Log.w(TAG, "反射接听失败，尝试其他方式", e)
            }
            
            // 备选方案：模拟按下接听键
            simulateAnswerKey()
            
            Log.d(TAG, "使用备选方案接听来电: $phoneNumber")
            
        } catch (e: Exception) {
            Log.e(TAG, "备选接听方案也失败", e)
        }
    }
    
    /**
     * 模拟按下接听键
     */
    private fun simulateAnswerKey() {
        try {
            // 模拟按下接听键的广播
            val intent = Intent(Intent.ACTION_MEDIA_BUTTON).apply {
                putExtra(Intent.EXTRA_KEY_EVENT, android.view.KeyEvent(
                    android.view.KeyEvent.ACTION_DOWN, 
                    android.view.KeyEvent.KEYCODE_HEADSETHOOK
                ))
            }
            sendOrderedBroadcast(intent, null)
            
            Log.d(TAG, "模拟接听键按下")
        } catch (e: Exception) {
            Log.e(TAG, "模拟接听键失败", e)
        }
    }

    /**
     * 拒绝来电
     */
    private fun rejectIncomingCall(phoneNumber: String?) {
        try {
            Log.d(TAG, "尝试拒绝来电: $phoneNumber")
            
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                telecomManager?.let { telecom ->
                    if (telecom.isInCall) {
                        // 使用Intent方式拒绝来电
                        rejectCallUsingIntent(phoneNumber)
                        Log.d(TAG, "成功拒绝来电: $phoneNumber")
                    } else {
                        Log.w(TAG, "当前没有来电需要拒绝")
                    }
                }
            } else {
                // Android O以下版本的处理
                rejectCallUsingIntent(phoneNumber)
            }
        } catch (e: SecurityException) {
            Log.e(TAG, "拒绝电话权限不足", e)
        } catch (e: Exception) {
            Log.e(TAG, "拒绝电话失败", e)
        }
    }
    
    /**
     * 使用Intent方式拒绝来电
     */
    private fun rejectCallUsingIntent(phoneNumber: String?) {
        try {
            // 创建拒绝电话的Intent - 使用有效的系统动作
            val rejectIntent = Intent("android.intent.action.DECLINE")
            rejectIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
            
            // 发送广播拒绝电话
            sendBroadcast(rejectIntent)
            
            Log.d(TAG, "使用Intent方式拒绝来电: $phoneNumber")
        } catch (e: Exception) {
            Log.e(TAG, "使用Intent拒绝电话失败", e)
            // 备选方案：使用反射或其他方式
            rejectCallFallback(phoneNumber)
        }
    }
    
    /**
     * 拒绝电话的备选方案
     */
    private fun rejectCallFallback(phoneNumber: String?) {
        try {
            // 使用反射调用TelecomManager的拒绝方法
            try {
                val telecomManagerClass = Class.forName("android.telecom.TelecomManager")
                val method = telecomManagerClass.getMethod("endCall")
                method.invoke(telecomManager)
                Log.d(TAG, "使用反射拒绝来电: $phoneNumber")
                return
            } catch (e: Exception) {
                Log.w(TAG, "反射拒绝失败，尝试其他方式", e)
            }
            
            // 备选方案：模拟按下拒绝键
            simulateRejectKey()
            
            Log.d(TAG, "使用备选方案拒绝来电: $phoneNumber")
            
        } catch (e: Exception) {
            Log.e(TAG, "备选拒绝方案也失败", e)
        }
    }
    
    /**
     * 模拟按下拒绝键
     */
    private fun simulateRejectKey() {
        try {
            // 模拟按下拒绝键的广播
            val intent = Intent(Intent.ACTION_MEDIA_BUTTON).apply {
                putExtra(Intent.EXTRA_KEY_EVENT, android.view.KeyEvent(
                    android.view.KeyEvent.ACTION_DOWN, 
                    android.view.KeyEvent.KEYCODE_ENDCALL
                ))
            }
            sendOrderedBroadcast(intent, null)
            
            Log.d(TAG, "模拟拒绝键按下")
        } catch (e: Exception) {
            Log.e(TAG, "模拟拒绝键失败", e)
        }
    }

    /**
     * 创建通知渠道
     */
    private fun createNotificationChannel() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            val channel = NotificationChannel(
                CHANNEL_ID,
                "电话接听服务",
                NotificationManager.IMPORTANCE_LOW
            ).apply {
                description = "电话接听服务正在运行，用于拦截和接听来电"
            }
            
            val notificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
            notificationManager.createNotificationChannel(channel)
        }
    }

    /**
     * 创建前台服务通知
     */
    private fun createNotification(): Notification {
        return NotificationCompat.Builder(this, CHANNEL_ID)
            .setContentTitle("电话接听服务")
            .setContentText("正在监听来电")
            .setSmallIcon(android.R.drawable.ic_menu_call)
            .setPriority(NotificationCompat.PRIORITY_LOW)
            .build()
    }

    override fun onDestroy() {
        super.onDestroy()
        Log.d(TAG, "电话接听服务已销毁")
        currentCall = null
        telecomManager = null
    }

    companion object {
        const val ACTION_ANSWER_CALL = "com.ashley.phonemsn.ACTION_ANSWER_CALL"
        const val ACTION_REJECT_CALL = "com.ashley.phonemsn.ACTION_REJECT_CALL"
        const val EXTRA_PHONE_NUMBER = "phone_number"
        
        /**
         * 启动接听服务
         */
        fun startService(context: Context, phoneNumber: String? = null) {
            val intent = Intent(context, CallAnswerService::class.java).apply {
                action = ACTION_ANSWER_CALL
                putExtra(EXTRA_PHONE_NUMBER, phoneNumber)
            }
            
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                context.startForegroundService(intent)
            } else {
                context.startService(intent)
            }
        }
        
        /**
         * 停止接听服务
         */
        fun stopService(context: Context) {
            val intent = Intent(context, CallAnswerService::class.java)
            context.stopService(intent)
        }
    }
}